﻿using mshtml;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Controls;
namespace LunarSF.SHomeWorkshop.LunarMarkdownEditor.Utils
{
    public class Web
    {
        public Web()
        {
            this.webBrowser = new WebBrowser();
            this.webBrowser.LoadCompleted += WebBrowser_LoadCompleted;
        }

        public Web(WebBrowser webBrowser)
        {
            if (webBrowser == null)
                webBrowser = new WebBrowser();
            this.webBrowser = webBrowser;
            this.webBrowser.LoadCompleted += WebBrowser_LoadCompleted;
        }

        public Uri Source
        {
            get
            {
                return webBrowser != null ? webBrowser.Source : null;
            }
            set
            {
                if (webBrowser != null)
                    webBrowser.Source = value;
            }
        }

        /// <summary>
        /// 简单地封装一下，其实就是 WebBrowser 的 LoadCompleted 事件。
        /// </summary>
        public event EventHandler<System.Windows.Navigation.NavigationEventArgs> LoadCompleted;

        protected void OnLoadCompleted(object sender, System.Windows.Navigation.NavigationEventArgs e)
        {
            if (LoadCompleted != null)
            {
                LoadCompleted(sender, e);
            }
        }

        private void WebBrowser_LoadCompleted(object sender, System.Windows.Navigation.NavigationEventArgs e)
        {
            OnLoadCompleted(sender, e);
        }

        private WebBrowser webBrowser;

        public WebBrowser WebBrowser { get { return webBrowser; } }

        /// <summary>
        /// Inject javascript code to previewFrame(webBrowser).
        /// </summary>
        public bool InjectJSCode(string jscode)
        {
            var web = this.webBrowser;
            if (web == null) return false;
            try
            {
                mshtml.HTMLDocument htmlDoc = web.Document as mshtml.HTMLDocument;
                var head = htmlDoc.getElementsByTagName("head").Cast<HTMLHeadElement>().First();
                var script = (IHTMLScriptElement)htmlDoc.createElement("script");
                script.text = jscode;
                head.appendChild((IHTMLDOMNode)script);
                return true;
            }
            catch
            {
                return false;
            }
        }

        /// <summary>
        /// Inject javascript file link to previewFrame(webBrowser).
        /// </summary>
        public bool InjectJSFile(string jsFileRelativePath)
        {
            var web = this.webBrowser;
            if (web == null) return false;
            try
            {
                mshtml.HTMLDocument htmlDoc = web.Document as mshtml.HTMLDocument;
                var head = htmlDoc.getElementsByTagName("head").Cast<HTMLHeadElement>().First();
                var script = (IHTMLScriptElement)htmlDoc.createElement("script");
                script.src = jsFileRelativePath;
                head.appendChild((IHTMLDOMNode)script);
                return true;
            }
            catch
            {
                return false;
            }
        }

        /// <summary>
        /// Get changed(by javascript) html text from previewFrame.
        /// </summary>
        public string GetHtml()
        {
            var header = "<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Transitional//EN\" \"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd\">\n" +
                         "<html xmlns=\"http://www.w3.org/1999/xhtml\" >\n";
            var tail = "\n</html>";
            var web = this.webBrowser;
            if (web == null) { return "未找到 WebBrowser ！请检查预览区中是否正在预览 Html 网页文档！"; }
            try
            {
                var html = web.InvokeScript("getHtml") as string;
                if (string.IsNullOrWhiteSpace(html))
                {
                    return "没有在预览区中找到 Html 文档的内容文本。请检查预览区中是否正在预览 Html 网页文档或 Html 文档的内容是否正确！";
                }
                return $"{header}{html}{tail}";
            }
            catch (Exception ex)
            {
                return ex.Message;
            }
        }

        /// <summary>
        /// Run javascript code in previewFrame(webBrowser).
        /// </summary>
        public string RunJS(string jsCode)
        {
            if (string.IsNullOrWhiteSpace(jsCode)) return $"{nameof(jsCode)}不能为空白或 null。";
            var webBrowser = this.webBrowser;
            if (webBrowser == null) { return "未找到 WebBrowser ！请检查预览区中是否正在预览 Html 网页文档！"; }
            try
            {
                return webBrowser.InvokeScript(jsCode) as string;
            }
            catch (Exception ex)
            {
                return ex.Message;
            }
        }
    }
}
